using Sirenix.OdinInspector;
using UnityEngine;

namespace sty.zytc
{
    public class Dashboard : MonoBehaviour
    {
        [LabelText("指针")]
        public Transform needle;
        [LabelText("旋转最小值")]
        public float needleMinRotate = 0f;
        [LabelText("旋转最大值")]
        public float needleMaxRotate = 100f;
        [LabelText("模拟量最小值")]
        public float analogMinValue = 0f;
        [LabelText("模拟量最大值")]
        public float analogMaxValue = 250f;
        [LabelText("需要映射的模拟量")]
        public float value;
        [LabelText("旋转速度")]
        public float rotationSpeed = 2f;

        private float targetValue = 0f;    
        private float currentValue = 0f;   
        private Quaternion initLocalRotation;
        private void Start()
        {
            initLocalRotation = needle.localRotation;
        }

        void Update()
        {
            targetValue = Mathf.Clamp(映射值(value), needleMinRotate, needleMaxRotate);
            currentValue = Mathf.Lerp(currentValue, targetValue, rotationSpeed * Time.deltaTime);
            // 当接近目标值时更新当前值
            if (Mathf.Abs(currentValue - targetValue) < 0.1f)
            {
                currentValue = targetValue;
            }
            UpdateRotation();
        }

        private void UpdateRotation()
        {
            float normalizedValue = Mathf.InverseLerp(needleMinRotate, needleMaxRotate, currentValue);
            float rotationZ = normalizedValue * needleMaxRotate;
            needle.localRotation = initLocalRotation * Quaternion.Euler(0f, 0f, -rotationZ);
        }

        private float 映射值(float value)
        {
            value = Mathf.Clamp(value, analogMinValue, analogMaxValue);
            float bRange = analogMaxValue - analogMinValue;
            float aRange = needleMaxRotate - 0f;
            return ((value - analogMinValue) / bRange) * aRange;
        }
    }
}
